package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

//    @Value("${dayParam}")
//    private Integer dayParam;
    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {

        //1.查询最近5天的所有的文章
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-500);
        List<ApArticle> apArticleList = apArticleMapper.loadArticleListByDays(calendar.getTime());

        //2.计算文章的分值（加权处理）
        List<HotArticleVo> hotArticleVos = computeHotArticle(apArticleList);

        //3.给每个频道找出30条分值较高的文章存入到redis
        cacheTagToRedis(hotArticleVos);

    }

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private CacheService cacheService;

    /**
     * 给每个频道找出30条分值较高的文章存入到redis
     * @param hotArticleVos
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVos) {

        //查询频道
        ResponseResult responseResult = wemediaClient.findAllChannel();
        if(responseResult.getCode().equals(200)){
            List<WmChannel> wmChannels = JSON.parseArray(JSON.toJSONString(responseResult.getData()), WmChannel.class);

            for (WmChannel wmChannel : wmChannels) {
                //找出频道所对应的文章
                //给文章按照分值排序，并截取前30个文章，
                List<HotArticleVo> hotArticleVoList = hotArticleVos.stream()
                        .filter(x -> x.getChannelId().equals(wmChannel.getId()))  //找出对应频道的文章数据
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())  //排序，按照分值排序 降序
                        .limit(30)
                        .collect(Collectors.toList());

                //存入redis
                cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+wmChannel.getId(), JSON.toJSONString(hotArticleVoList));
            }
        }

        //给推荐设置缓存数据

        List<HotArticleVo> hotArticleVoList = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())  //排序，按照分值排序 降序
                .limit(30)
                .collect(Collectors.toList());

        //存入redis
        cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG, JSON.toJSONString(hotArticleVoList));
    }

    /**
     * 计算文章分值
     * @param apArticleList
     * @return
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> apArticleList) {

        List<HotArticleVo> hotArticleVoList = new ArrayList<>();

        if(apArticleList != null && apArticleList.size() > 0){
            for (ApArticle apArticle : apArticleList) {
                HotArticleVo hot = new HotArticleVo();
                BeanUtils.copyProperties(apArticle,hot);
                Integer score = computeScore(apArticle);
                hot.setScore(score);
                hotArticleVoList.add(hot);

            }
        }

        return hotArticleVoList;

    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {

        Integer score = 0;
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }

        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }

        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }

        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
